﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace RuntimeConsole
{
    class FloatButton : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    {

        public RuntimeConsole console;
        private bool dragging;

        private void Start()
        {
            gameObject.GetComponent<Button>().onClick.AddListener(onClick);
        }

        private void onClick()
        {
            if(!dragging && console)
            {
                console.Showing = true;
            }
        }

        // begin dragging
        public void OnBeginDrag(PointerEventData eventData)
        {
            SetDraggedPosition(eventData);
            dragging = true;
        }

        // during dragging
        public void OnDrag(PointerEventData eventData)
        {
            SetDraggedPosition(eventData);
        }

        // end dragging
        public void OnEndDrag(PointerEventData eventData)
        {
            SetDraggedPosition(eventData);
            dragging = false;
        }

        /// <summary>
        /// set position of the dragged game object
        /// </summary>
        /// <param name="eventData"></param>
        private void SetDraggedPosition(PointerEventData eventData)
        {
            var rt = gameObject.GetComponent<RectTransform>();

            // transform the screen point to world point int rectangle
            Vector3 globalMousePos;
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
            {
                rt.position = globalMousePos;
            }
        }
    }
}
